package wang.aweb.childcar.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wang.aweb.childcar.exception.CarException;
import wang.aweb.childcar.exception.CarExceptionEnum;
import wang.aweb.childcar.model.dao.MoneyMealMapper;
import wang.aweb.childcar.model.pojo.MoneyMeal;
import wang.aweb.childcar.model.vo.MoneyMealVO;
import wang.aweb.childcar.service.MoneyMealService;

import java.util.ArrayList;
import java.util.List;
@Service
public class MoneyMealServiceImpl implements MoneyMealService {
    @Autowired
    private MoneyMealMapper moneyMealMapper;
    @Override
    public List<MoneyMealVO> getList(){
        List<MoneyMeal> moneyMeals=moneyMealMapper.selectList();
        List<MoneyMealVO> moneyMealVOS=moneyMealsToMoneyMealVOS(moneyMeals);
        return moneyMealVOS;
    }
    @Override
    public MoneyMeal findById(Integer mealId){
        MoneyMeal moneyMeal=moneyMealMapper.selectByPrimaryKey(mealId);
        return moneyMeal;
    }
    @Override
    public void disableOrEnable(Integer id) {
        MoneyMeal moneyMeal=moneyMealMapper.selectByPrimaryKey(id);
        if(moneyMeal.getStatus()==1){
            moneyMeal.setStatus(0);
        }else{
            moneyMeal.setStatus(1);
        }
        int count=moneyMealMapper.updateByPrimaryKeySelective(moneyMeal);
        if(count==0){
            throw new CarException(CarExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public List<MoneyMealVO> getEnableList() {
        List<MoneyMeal> moneyMealList=moneyMealMapper.selectEnableList();
        List<MoneyMealVO> moneyMealVOList=moneyMealsToMoneyMealVOS(moneyMealList);
        return moneyMealVOList;
    }

    public List<MoneyMealVO> moneyMealsToMoneyMealVOS(List<MoneyMeal> moneyMeals){
        List<MoneyMealVO> moneyMealVOS=new ArrayList<>();
        for (int i = 0; i < moneyMeals.size(); i++) {
            MoneyMeal moneyMeal =  moneyMeals.get(i);
            moneyMealVOS.add(getMoneyMealVO(moneyMeal));
        }
        return moneyMealVOS;
    }
    public MoneyMealVO getMoneyMealVO(MoneyMeal moneyMeal){
        MoneyMealVO moneyMealVO=new MoneyMealVO();
        BeanUtils.copyProperties(moneyMeal,moneyMealVO);
        moneyMealVO.setPrice((float)moneyMeal.getPrice()/100);
        moneyMealVO.setRealprice((float)moneyMeal.getRealprice()/100);
        moneyMealVO.setCreate_time(moneyMeal.getCreateTime());
        return moneyMealVO;
    }
}
